package cn.huijielong.modules.oss.cloud;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import cn.huijielong.common.exception.VSException;
import cn.huijielong.common.validator.Assert;
import cn.huijielong.modules.oss.entity.Oss;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.http.Response;

public class QiniuCloudStorage extends CloudStorage {

	private Logger logger = LoggerFactory.getLogger(QiniuCloudStorage.class);
    private UploadManager uploadManager;
    private String token;
    private String bucket;
    private final static long expires=60*60*12; //有效时长，单位秒。默认3600s


    public QiniuCloudStorage(Oss oss,String bucket){
    	Assert.isBlank(oss.getQiniuAccessKey(), "七牛云配置config中qiniuAccessKey不能为空");
    	Assert.isBlank(oss.getQiniuSecretKey(), "七牛云配置config中qiniuSecretKey不能为空");
        this.oss = oss;
        this.ossBucket=oss.getBucket(bucket);
        this.bucket=bucket;
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(oss.getQiniuAccessKey(), oss.getQiniuSecretKey()).
                uploadToken(bucket);
    }

    @Override
    public String upload(byte[] data, String path) {
    	if(path.startsWith("/")) {
        	path=path.substring(1);
        }
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            
        } catch (Exception e) {
            throw new VSException("上传文件失败，请核对七牛配置信息", e);
        }
        if(ossBucket.getDomain().endsWith("/"))
        	return ossBucket.getDomain() + path;
        else
        	return ossBucket.getDomain() +"/"+ path;
        
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new VSException("上传文件失败", e);
        }
    }

    @Override
    public boolean delete(String path) {
    	return delete(path, bucket);
    }
    @Override	
    public boolean delete(String path,String bucket) {
		try {
			if(path.startsWith(ossBucket.getDomain())) {
				path=path.substring(ossBucket.getDomain().length()+1);
			}
			Auth auth=Auth.create(oss.getQiniuAccessKey(), oss.getQiniuSecretKey());
			//实例化一个BucketManager对象
	        BucketManager bucketManager = new BucketManager(auth, new Configuration(Zone.autoZone()));
	        Response resp=bucketManager.delete(bucket, path);
			if (!resp.isOK()) {
				throw new RuntimeException(resp.toString());
			}
		} catch (Exception e) {
			logger.error("七牛删除文件出错", e);
			throw new VSException("七牛删除文件出错：" ,e);
		}
		return true;
	}
    @Override
    public boolean deleteBatch(String ... path) {
    	return deleteBatch(bucket,path);
    }
    @Override
    public boolean deleteBatch(String bucket,String ... path) {
    	if(path.length==0)
    		return true;
		try {
			String[] keys=new String[path.length];
			for(int i=0;i<path.length;i++) {
				if(path[i].startsWith(ossBucket.getDomain())) {
					keys[i]=path[i].substring(ossBucket.getDomain().length()+1);
				}else {
					keys[i]=path[i];
				}
			}
			
			Auth auth=Auth.create(oss.getQiniuAccessKey(), oss.getQiniuSecretKey());
			//实例化一个BucketManager对象
	        BucketManager bucketManager = new BucketManager(auth, new Configuration(Zone.autoZone()));
	        BucketManager.BatchOperations operations=new BucketManager.BatchOperations();
	        Response resp=bucketManager.batch(operations.addDeleteOp(bucket, keys));
			if (!resp.isOK()) {
				throw new RuntimeException(resp.toString());
			}
		} catch (Exception e) {
			logger.error("七牛批量删除文件出错", e);
			throw new VSException("七牛批量删除文件出错：" ,e);
		}
		return true;
	}

    public String getToken() {
        return token;
    }

	@Override
	public String getPrivateUrl(String targetUrl) {
		Auth auth=Auth.create(oss.getQiniuAccessKey(), oss.getQiniuSecretKey());
		return auth.privateDownloadUrl(targetUrl,expires);
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

}
